package com.shopping.config;

import com.shopping.security.CustomUserDetailsService;
import com.shopping.security.JwtRequestFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private JwtRequestFilter jwtRequestFilter;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                // 禁用CSRF
                .csrf().disable()
                // 启用CORS
                .cors().and()
                // 配置会话管理
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                // 配置授权规则
                .authorizeRequests()
                // 允许公开访问的路径
                .antMatchers("/api/user/register", "/api/user/login").permitAll()
                .antMatchers(org.springframework.http.HttpMethod.GET, "/api/product/**").permitAll()
                // 评论接口权限配置
                .antMatchers(HttpMethod.GET, "/api/comments/product/**").permitAll()  // 允许查看评论
                .antMatchers(HttpMethod.GET, "/api/comments/product/*/rating").permitAll()  // 允许查看评分
                .antMatchers(HttpMethod.GET, "/api/comments/user").authenticated()  // 需要登录才能查看自己的评论
                .antMatchers(HttpMethod.POST, "/api/comments/**").authenticated()  // 需要登录才能评论
                .antMatchers(HttpMethod.PUT, "/api/comments/**").authenticated()  // 需要登录才能修改评论
                .antMatchers(HttpMethod.DELETE, "/api/comments/**").authenticated()  // 需要登录才能删除评论
                .antMatchers("/api/images/**").permitAll()
                .antMatchers("/api/upload/**").permitAll()
                .antMatchers("/uploads/**").permitAll()
                // 留言板公开接口
                .antMatchers("/api/message/list").permitAll()
                // 需要认证的用户路径
                .antMatchers("/api/user/info").authenticated()  // 获取用户信息
                .antMatchers("/api/user/password").authenticated()  // 修改密码
                .antMatchers("/api/user/points").authenticated()  // 更新积分
                .antMatchers("/api/user/list").hasRole("ADMIN")  // 获取用户列表需要管理员权限
                .antMatchers("/api/user/{userId}/**").hasRole("ADMIN")  // 管理员操作用户的接口
                // 需要认证的其他路径
                .antMatchers("/api/cart/**").authenticated()
                .antMatchers("/api/order/**").authenticated()
                .antMatchers("/api/address/**").authenticated()
                .antMatchers("/api/message/user/current").authenticated()
                .antMatchers("/api/message/user/{userId}").authenticated()
                .antMatchers("/api/message/reply").authenticated()
                .antMatchers("/api/message/publish").authenticated()
                // 管理员路径需要管理员权限
                .antMatchers("/api/admin/**").hasRole("ADMIN")
                // 其他请求需要认证
                .anyRequest().authenticated()
                .and()
                // 添加JWT过滤器
                .addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("http://localhost:3000"));
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
        configuration.setAllowedHeaders(Arrays.asList("*"));
        configuration.setAllowCredentials(true);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}